#!/usr/bin/env node

// PWM信号验证脚本
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

console.log("🔍 PWM信号验证脚本");

// 验证PWM值转换
function calculateDutyCycle(value) {
  // value范围: -1到1映射到1.0ms到2.0ms
  let dutyCycleMs;
  if (value === 0) {
    dutyCycleMs = 1.5; // 中性位置
  } else {
    // 确保值在-1到1范围内
    value = Math.max(-1, Math.min(1, value));
    dutyCycleMs = 1.5 + (value * 0.5); // 范围: 1.0ms 到 2.0ms
  }
  
  // 限制范围确保安全
  dutyCycleMs = Math.max(1.0, Math.min(2.0, dutyCycleMs));
  
  return dutyCycleMs;
}

async function testPWMSignals() {
  console.log("\n🔧 测试PWM信号转换:");
  
  const testValues = [0, 0.5, -0.5, 1, -1];
  
  testValues.forEach(value => {
    const dutyCycle = calculateDutyCycle(value);
    console.log(`  值 ${value} => ${dutyCycle}ms 高电平`);
  });
  
  console.log("\n🔌 实际信号测试:");
  
  try {
    // 初始化引脚
    await execAsync('gpio -g mode 13 out');
    console.log("✅ 引脚13初始化为输出模式");
    
    // 测试不同值
    for (const value of testValues) {
      const dutyCycle = calculateDutyCycle(value);
      console.log(`\n测试值 ${value} (${dutyCycle}ms):`);
      
      // 发送信号并保持一段时间
      await sendPWMSignal(13, dutyCycle, 1000);
    }
    
    // 结束时发送中性信号
    console.log("\n发送中性信号...");
    await sendPWMSignal(13, 1.5, 1000);
    
    console.log("\n✅ PWM信号测试完成");
  } catch (error) {
    console.error("❌ PWM信号测试失败:", error.message);
  }
}

// 发送PWM信号的辅助函数
async function sendPWMSignal(pin, dutyCycleMs, durationMs) {
  const periodMs = 20; // 50Hz = 20ms周期
  const highTimeMs = dutyCycleMs;
  const lowTimeMs = periodMs - dutyCycleMs;
  
  const cycles = Math.floor(durationMs / periodMs);
  
  for (let i = 0; i < cycles; i++) {
    await execAsync(`gpio -g write ${pin} 1`);
    await sleep(highTimeMs);
    await execAsync(`gpio -g write ${pin} 0`);
    await sleep(lowTimeMs);
  }
}

// 精确延时函数（毫秒）
function sleep(ms) {
  return new Promise(resolve => {
    const start = Date.now();
    while (Date.now() - start < ms) {
      // 空循环等待
    }
    resolve();
  });
}

function main() {
  console.log("🚀 开始PWM信号验证");
  
  testPWMSignals();
}

main();